/* 
 * Spring mixin mybatis frame code general
 * Fu(iknoweth@yahoo.com) All rights reserved 
 * 
 */
package com.pricl.biz.file.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.pricl.biz.file.entity.FileInfo;
import com.pricl.biz.file.service.FileService;
import com.pricl.frame.core.E;
import com.pricl.frame.core.R;

/**
 * <p>
 * <strong>附件信息表</strong>Access Controller
 * </p>
 *
 */
@RequestMapping("/file")   
@Controller
public class FileController {  
	//private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	FileService service;

	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index() {
		return "/file/index";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String upload() {
		return "/file/upload";
	}

	/**
	 * <p>
	 * 文件上传
	 * </p>
	 * 
	 * @param item
	 * @param file
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public @ResponseBody R upload(FileInfo item, @RequestParam("file") MultipartFile file) {
		item.setOname(file.getOriginalFilename());
		item.setContentType(file.getContentType());
		item.setLength(file.getSize());
		try {
			//service.upload(item, file.getInputStream(), file.getSize());
			service.upload(item, file.getInputStream(), file.getSize(), file);
		} catch (IOException e) {
			throw new E("上传文件读写出错");
		} 
		return R.ok(item);
	}
	
	/**
	 * <p>
	 * 删除操作
	 * </p>
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody R delete(String id) {
		service.delete(id);
		return R.ok();
	}

	/**
	 * <p>
	 * 获取唯一信息
	 * </p>
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/get", method = RequestMethod.POST)
	public @ResponseBody FileInfo get(String id) {
		return service.findOne(id);
	}

	/**
	 * <p>
	 * 获取关联业务列表
	 * </p>
	 * 
	 * @param type
	 * @param bid
	 * @return
	 */
	@RequestMapping(value = "/links", method = RequestMethod.POST)
	public @ResponseBody List<FileInfo> links(String type, String bid) {
		return service.findLink(type, bid);
	}

	/**
	 * <p>
	 * 文件资源
	 * </p>
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{path}", method = RequestMethod.GET)
	public void resource(@PathVariable String path, HttpServletResponse response) {
		String[] paths = path.split(",");
		FileInfo file = null;
		if (paths.length == 1) {
			file = service.findOne(paths[0]);
		} else {
			file = service.findByType(paths[0], Integer.valueOf(paths[1]));
		}
		if (file != null) {
			try {
				response.sendRedirect(file.getPath() + "/" + file.getName());
			} catch (IOException e) {
			}
		}
	}

	/**
	 * <p>
	 * </p>
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/download", method = { RequestMethod.POST, RequestMethod.GET })
	public ResponseEntity<byte[]> download(String id) throws IOException {
		HttpHeaders headers = new HttpHeaders();
		FileInfo item = service.findOne(id);
		File file = service.getFile(item);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", item.getName());
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "/uploadVideo", method = RequestMethod.POST)
	public @ResponseBody R uploadVideo(FileInfo item, @RequestParam("file") MultipartFile file) {
		item.setOname(file.getOriginalFilename());
		item.setContentType(file.getContentType());
		item.setLength(file.getSize());
		try {
			service.uploadVideo(item, file.getInputStream(), file.getSize(), file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return R.ok("");
	}
	
	/**
	 * 
	 * @ClassName uploadVideo 
	 * @Description 上传视频
	 * @author zbs  @date 2017年8月3日 @company 车资道科技 
	 * 
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "/uploadVideo", method = RequestMethod.GET)
	public String uploadVideo(Model model,FileInfo file) {
		return "/file/uploadVideo";
	}
	
	@RequestMapping(value = "/uploadVideoAuth", method = RequestMethod.POST)
	public @ResponseBody R uploadVideoAuth(Model model,FileInfo file) {
		CreateUploadVideoResponse uploadAuthResponse = service.createUploadVideo(file);
		//model.addAttribute("createUpload", createUpload);
		return R.ok(uploadAuthResponse);
	}
	
	/**
	 * 
	 * @ClassName getPlayAuth 
	 * @Description  获取播放凭证 
	 * @author zbs  @date 2017年8月3日 @company 车资道科技 
	 * 
	 * @param videoId
	 * @return
	 */
	@RequestMapping(value = "/getPlayAuth", method = RequestMethod.POST)
	public @ResponseBody R getPlayAuth(@RequestParam("videoid")String videoId) {
		GetVideoPlayAuthResponse response= service.getVideoPlayAuth(videoId);
		return R.ok(200,response,"success");
	}
	
	@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
	public @ResponseBody R uploadFiles(FileInfo item, @RequestParam("files") MultipartFile[] files,HttpServletRequest req) throws IOException {
		try {
			for(MultipartFile file:files){
				item.setOname(file.getOriginalFilename());
				item.setContentType(file.getContentType());
				item.setLength(file.getSize());
				service.upload(item, file.getInputStream(), file.getSize(), file);
			}
		} catch (IOException e) {
			throw new E("上传文件读写出错");
		} 
		return R.ok(item);
	}
	
	@RequestMapping(value = "/uploadCkeditorImp", method = RequestMethod.POST)
	public @ResponseBody void uploadCkeditorImp(FileInfo item, @RequestParam("upload") MultipartFile file
			,HttpServletRequest request, HttpServletResponse response) {
		item.setOname(file.getOriginalFilename());
		item.setContentType(file.getContentType());
		item.setLength(file.getSize());
		
		
		
		 try {
	           // String path = request.getSession().getServletContext().getRealPath(UPLOAD_PATH);
	            //System.out.println(path);
//	            String path = proName + UPLOAD_PATH;
	            PrintWriter out = response.getWriter();
	            String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");
	            String fileName = file.getOriginalFilename();
	            String uploadContentType = file.getContentType();
	            String expandedName = "";
	            if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
	                // IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
	                expandedName = ".jpg";
	            } else if (uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")) {
	                // IE6上传的png图片的headimageContentType是"image/x-png"
	                expandedName = ".png";
	            } else if (uploadContentType.equals("image/gif")) {
	                expandedName = ".gif";
	            } else if (uploadContentType.equals("image/bmp")) {
	                expandedName = ".bmp";
	            } else {
	                out.println("<script type=\"text/javascript\">");
	                out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",''," + "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');");
	                out.println("</script>");
	                return;
	            }
	            if (file.getSize() > 1024 * 1024 * 2) {
	                out.println("<script type=\"text/javascript\">");
	                out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",''," + "'文件大小不得大于2M');");
	                out.println("</script>");
	                return;
	            }
	           // DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
	           // fileName = df.format(new Date()) + expandedName;
	            //file.transferTo(new File(path + File.separator + fileName));
	            
	            try {
	    			//service.upload(item, file.getInputStream(), file.getSize());
	    			service.upload(item, file.getInputStream(), file.getSize(), file);
	    		} catch (IOException e) {
	    			throw new E("上传文件读写出错");
	    		} 
	            
	            // 返回"图像"选项卡并显示图片 request.getContextPath()为web项目名
	            out.println("<script type=\"text/javascript\">");
	            //out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'" + "../upload/img/" + fileName + "','')");
	            out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'" + item.getFileUrl() + "','')");
	            out.println("</script>");
	            return;
	        } catch (IllegalStateException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
		
		
		
		
		
		//return R.ok(item);
	}
}
